<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
		<SCRIPT LANGUAGE="JavaScript" SRC="particles.js"></SCRIPT>
		<SCRIPT LANGUAGE="JavaScript" SRC="level.js"></SCRIPT>
		<SCRIPT LANGUAGE="JavaScript" SRC="keyboard.js"></SCRIPT>
		
		
		<title>space_def</title>

	<script>
		
		// ######################### [Init] ##########################	
	
		var ctx;
		var canvas;
		var nave;
		var estado = new GameState();
		var motor = new Engine();
		var strategia = new Estrategy();
		
		var flotaArray = new Array();
		var enemyArray = new Array();	
		var special_weapon = new Array();
		var nave_weapon_array = new Array();
		
		
		// ######################### Objects ##########################
		
	
		
		var cache_image;
		var imagen; 
	
		
			function init(){
				
				var sprites = ["f22_moi__ship.PNG","enemy_model_2.png","MOI1.PNG","b2_finalBoss.PNG"];
				loadImg(sprites);
			}
			
			//iniciamos el proceso aqui & bind del teclado.
			function start() {
				
				estado.inicializar = true; 
				
				globalCompositeOperation = 'copy';
				
				window.addEventListener('keydown', doKeyDown, true);
				window.addEventListener('keyup', doKeyUp, true);
				
				
				canvas = document.getElementById('canvas')
				ctx = canvas.getContext('2d');

		
			//configuring
				//definiendo la configuracion de las fuentes.
				ctx.font = '12px Courier';
				
				nave = new Ship();
				animLoop(iniciarJuego);

			}
			
			
		function cargarImagen(img_src){
			return cache_image[img_src];
		}	
		
		function loadImg(src){
				
				
				var index = 0; 
			//	var imagen = [new Image(),new Image(),new Image()];
				var imagen = [];
				for (var i=0; i < src.length; i++) {
			
				imagen[i] =  new Image();
				var x = 0; 
				imagen[i].onload = function(){
				    
				    if(cache_image == null) cache_image = {};
				    cache_image[src[x]] = imagen[x];
					//alert("load"+src[x]);
					
					x++;
					if(x == src.length)start();
					
			
				}
				
				imagen[i].src = src[i];
						
				};	
				
			}
		

		
		function Flota(){
			this.flota_enemiga = new Array();
			this.estrategia = new Estrategy();
			this.x = 0;
			this.y = 0; 
			this.side_fin = false; 
			this.side_start = false; 
			this.reset = function(){
				
				this.flota_enemiga = new Array();
				this.estrategia = new Estrategy();
			}
			
			
			this.ejecutar  = function(delta){
				
				var value_y =  delta / 60;
				var value_x =  delta / 5;
				var posy = 0; 
				var posx = value_x;
				if(this.side_fin)posx= -value_x;	 			
				if(this.side_start)posx= value_x;
				
				
			 	posy  = value_y;
			 	
			 	
				this.draw(delta,posx,posy);			
			}
			
			this.draw  = function(delta, posx , posy){
				
					for (var i=0; i < this.flota_enemiga.length; i++) {
						var enemy_tmp = this.flota_enemiga[i];	
						
						if(enemy_tmp.live && enemy_tmp != null){	
							enemy_tmp.get_shoot();
							enemy_tmp.shoot = intelE(nave, enemy_tmp);				  
				
						if(enemy_tmp.shoot == 3) enemy_tmp.disparar();	
						
						if(enemy_tmp.y > canvas.height){nave.gameover();}
									
				
						// limitaciones de la pantalla.
						if(enemy_tmp.x >= this.estrategia.x2){
							this.side_fin = true;
							this.side_start = false;
						}
						if(enemy_tmp.x <= this.estrategia.x1){ 
							this.side_start = true;
							this.side_fin = false;
						}				
					
					
						if(enemy_tmp.style == "D"){
							if(enemy_tmp.y > 100) posy-= Math.random() * 1;
							this.estrategia.thinking_time -= 1; 
							if(this.estrategia.thinking_time == 0){
								this.estrategia.thinking_time = 1000; 
								this.estrategia.x2 = nave.x + Math.random() * 200; 
								this.estrategia.x1 = nave.x - Math.random() * 200;
								enemy_tmp.get_shoot();
							}
						}
						
							if(enemy_tmp.style == "Z"){
							if(enemy_tmp.y > 100) posy-= Math.random() * 1;
							this.estrategia.thinking_time -= 1; 
							if(this.estrategia.thinking_time == 0){
								this.estrategia.thinking_time = 1000; 
								this.estrategia.x2 = nave.x+Math.random() * 600; 
								this.estrategia.x1 = nave.x-Math.random() * 600;
							}
						}
						
						
						enemy_tmp.shock();
						
						//Dibujado de la nave
						enemy_tmp.x += posx; 
						enemy_tmp.y += posy;
						enemy_tmp.paint(delta);

						}
						
				     
						
					};
					
						
				}
			
			}
		
		
		function GameState(){
			this.inicializar = false; 
			this.game = false; 
			this.stage = 0; 
			this.enemys = 0; 
			this.next = true;		
			this.gameOver = false; 
			this.score = 0; 
			this.colision = false; 
		}
		
		function Engine(){
			this.animationShoot = false; 
			this.pos_x = 0; 
			this.pos_y =-35;		
		}
		
		function Estrategy(){
			this.thinking_time = 1000; 
			this.x1  = 10; 
			this.x2 = 900; 
			
		}
		
		
		// #################################### WEAPONS ######################################## 
		
		function Bullet(){
			this.live = false; 
			this.type = 0; 			
			this.y = 540; 
			this.x = 0; 
			this.explode = false;
			this.how = "";
			this.draw = function(speed){
			
				speed = speed /3;
						
				if(this.live){
					if(this.how == "N")
						this.y -= speed;
							
					if(this.how == "E")
						this.y += speed;
					
					
					if(this.y > 600)this.live = false;	
					ctx.save();
					ctx.fillStyle = "rgba(255, 255, 255, .9)"; 
				 	ctx.fillRect(this.x, this.y, 5, 5);  
					ctx.restore();
			
				}
			}	
		}
		
		function SBullet(){
			this.live = false; 
			this.type = 0; 	
			this.y = 0; 
			this.x = 0; 
			this.size = 1; 	
			this.expansive =5;	
			this.position = new Array(); 
			this.explode = false;
			this.how;
			this.angulo = (Math.PI*2); 
			this.tamano = 0;			
			this.avanzar = function(speed){					
				this.y -= speed;			
			}
			this.inicializar = false; 
			this.draw = function(delta){	
			var speed = delta/5; 
			
			// inicializacion de la arma.
			if(!this.inicializar){
				for (var i=0; i < this.size; i++) {
				  var location = new LocationObj();
				  location.x = this.x; 
				  location.y = this.y; 
				  this.position.push(location);  
				};
					 
					 this.inicializar = true; 
				}
				
				if(this.how == "Z"){
				
				// draw de bullets.
				for (var i=0; i < this.size; i++) {
					var location = this.position[i];
					
					this.tamano += 0.5; 
					
					location.y += Math.sin(this.angulo * (i* 0.05))  + speed;
					
					//intento crear una lluvia
					location.x += (i*0.5);
					
					
					ctx.fillRect(location.x, location.y, this.expansive,this.expansive);
					//this.position[i] = location; 
					
					
				}
				
				}	
				

					
						// inicializacion de la arma.
				
				
				if(this.how == "D"){
				
				// draw de bullets.
				for (var i=0; i < this.size; i++) {
					var location = this.position[i];
					
					this.tamano += 0.5; 
					
					location.y += Math.sin(this.angulo* (i*.2)) + speed;
					
					//intento crear una lluvia
					location.x += (i*2.5);
					
					ctx.fillRect(location.x, location.y, this.expansive,this.expansive);
					//this.position[i] = location; 
					
					
				}
				
				}
					
				
							
			
			}	
		}
		
		// #################################### WEAPONS ######################################## 
		
		function LocationObj(){
			this.x = 0; 
			this.y = 0; 
		}
		
		function Ship(){
			this.imagen = cargarImagen("f22_moi__ship.PNG");		
			
			this.img_cargada = false; 
			this.x = 0;
  		  	this.y = 550;
			this.move_max_x = false; 
			this.move_min_x = false;
			this.shot = false; 
			this.lives = 1; 
			this.gameover = function(){
						generateParticles(this.x,this.y, 150, 250,3);
						nave.lives = -1; 
				
			}
			this.collide = function(weapon){
		 			
		 			// revision si existe collision entre dos objetos.
		 			var respuesta = check_collision(weapon, this);
		 			
		 			if(!estado.gameOver && respuesta){		
						this.gameover();
					}
		 		
		 	}	
					
		}
		
		function Enemys() {
		  this.pensar = new Estrategy();
		  this.imagen = cargarImagen("enemy_model_2.png");		  
		  this.img_cargada = false; 
		  this.x = 10;
  		  this.y = 0;
  		  this.live = false;
  		  this.agresive = 0; 
  		  this.shoot =  1;  // 1 = wait, 2 = shoot , 3= reload;  
  		  this.style = "E"
  		  this.orientacion = 0;
  		  this.life = 1; 
  		  this.bullet; 
  		  
  		 // ######################### Calculando si es momento de disparar [pequeño retardo para que no acribillen] ##########################
  		  this.get_shoot = function (argument) {			  	
				
			
				if(this.agresive >0){
					this.agresive -= 1; 
					this.shoot = 1;									
					
				}else{
					this.agresive =  Math.round(Math.random() * 50)+10;
					this.shoot = 2;
				}	
			
		  }
			    
		  // ######################### Disparo ##########################
		  this.disparar = function(){		 		 	
		 		 	
		 		 	this.shoot = 1;  //reload weapon.
					
		 		 	motor.animationShoot = true; //draw the bullet.
		 		 		
		 		 	if(this.style == "Z"){
		 		 		var weapon = new SBullet();
						weapon.live = true;
					    weapon.x = this.x + (this.imagen.width /2);
					    weapon.y = this.y + this.imagen.height; 
					    weapon.how = this.style;
					    weapon.size = 10;
					    this.bullet = weapon; 
					    weapon.expansive = 6;
					   
					    special_weapon.push(weapon);
			 		}
		 		 	
		 		 	if(this.style == "D"){
		 		 		var weapon = new SBullet();
						weapon.live = true;
						weapon.x = this.x + (this.imagen.width /2);
					    weapon.y = this.y + this.imagen.height; 
					    weapon.how = this.style;
					    this.bullet = weapon; 
					    weapon.expansive = 6;
					     weapon.size = 4;
					    special_weapon.push(weapon);
			 		}
					if(this.style == "E" || this.style == "C" || this.style == "X"){
			 		 	var weapon = new Bullet();
						weapon.live = true;
					    weapon.x = this.x + (this.imagen.width /2);
					    weapon.y = this.y + this.imagen.height; 
					    weapon.how = this.style;
					    this.bullet = weapon; 
					    special_weapon.push(weapon);
				   }
				   
		  }
		  
		  this.shock = function(){
		  	
		  	for (var i=0; i < nave_weapon_array.length; i++) {
			  this.collide(nave_weapon_array[i]);
			};
		  }
		 		 
		 	this.collide = function(weapon){
		 			
		 			// revision si existe collision entre dos objetos.
		 			var respuesta = check_collision(weapon, this);
		 			
		 			if(!estado.gameOver && respuesta){		
						estado.score += 100;
						this.life -=1;
									
						if(this.life <=0){
							this.live = false;
							estado.enemys -= 1;
							generateParticles(weapon.x,weapon.y, 30, 30,3);
						}
									
						generateParticles(weapon.x,weapon.y, 20, 20,4);
					}
		 		
		 	}	 
		 	
		 	 this.paint = function(delta){
			
				ctx.save(); 
				 
				
				ctx.drawImage(this.imagen,this.x,this.y);  
				ctx.restore();
			 }
		 	
		 	
  		  
  		 }

		// ######################### Objects ##########################
		
		
		
		
		
			// requestAnim shim layer by Paul Irish
			window.requestAnimFrame = (function() {
				return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
				function(/* function */callback, /* DOMElement */element) {
					window.setTimeout(callback, 1000 / 30);
				};

			})();
			
			//motor de animacion.
			function animLoop(render) {
				var running, lastFrame = +new Date;

				var raf = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || window.requestAnimationFrame;

				function loop(now) {
					// stop the loop if render returned false
					if(running !== false) {
						raf(loop);
						var intervalo = (now - lastFrame);
						if(intervalo < 2000) {
							running = render(intervalo);
						}
						lastFrame = now;
					}
				}
				
				loop(lastFrame);
			}

			function iniciarJuego(delta) {
	
				
				if(estado.inicializar)
				{										
					cargarFase(estado.stage);					
					estado.inicializar = false;
				}
				
				
				if(estado.next && estado.enemys <= 0)
				{
					flotaArray = new Array();
					estado.next = false; 
					estado.stage += 1; 
					cargarFase(estado.stage);
					//cleanMem();	
				
				}
				
				

				draw(delta);				
			}
	
			function cargarFase(fase)
			{
				var stage = getEsquema(fase);
				
				
				
				for (var i=0; i < stage.length; i++) {
					var obj =  stage[i]; 
				  
				  	if(obj == "0"){	motor.pos_x += 40; 	}
				  	
				  	
				  	if(obj == "Z"){				  		
				  		var tmp = dibujarSetEnemigo(1, motor.pos_x, motor.pos_y,obj);
				  		flotaArray.push(tmp);
				  		
				  	}

				  	if(obj == "D"){				  		
				  		var tmp = dibujarSetEnemigo(3, motor.pos_x, motor.pos_y,obj);
				  		flotaArray.push(tmp);
				  		
				  	}
				  	if(obj == "X"){				  		
				  		var tmp = dibujarSetEnemigo(10, motor.pos_x, motor.pos_y,obj);
				  		flotaArray.push(tmp);
				  		
				  	}				  	
				  	if(obj == "C"){				  	
				  		var tmp = dibujarSetEnemigo(60, motor.pos_x, motor.pos_y, obj);
				  		flotaArray.push(tmp);
				  		
				  	}
				  	
				  	motor.pos_y = motor.pos_y - 20;
				  	
				};
			
				estado.stage++;
				motor.pos_y =0;
				
			}
			
			
			
				function dibujarSetEnemigo(size, pos_x, pos_y, type){
					
					
					var flota = new Flota();
				
					var posicion_x = pos_x; 
					var posicion_y = pos_y;
					var filas = 5; 
					if(type == "C")filas = 15;
					
					for (var i=0; i < size; i++) {
						
						var enemigo = new Enemys();
					
						
						
						
						if((i % filas) == 0 && i > 1){
							
							 
							posicion_x = pos_x;
							posicion_y -= enemigo.imagen.height;		
						}
						
						posicion_x += (enemigo.imagen.width);
										
						enemigo.x  = posicion_x;
						enemigo.y = posicion_y; 
						enemigo.live = true; 
					
						if(type == "D"){
							enemigo.imagen = cargarImagen("MOI1.PNG"); 
							enemigo.style = "D";
							enemigo.agresive =  Math.round(Math.random() * 20);
							
							enemigo.life = 5;
						}
						
						if(type == "Z"){
							enemigo.imagen = cargarImagen("b2_finalBoss.PNG"); 
							enemigo.style = "Z";
							enemigo.agresive =  Math.round(Math.random() * 20);
							
							enemigo.life = 20;
						}
						
						
						if(type == "C")
					  	 enemigo.style = "E";
					  	 enemigo.agresive =  Math.round(Math.random() * 30);
					  	
					  	if(type == "X"){
						 enemigo.style = "E"; 
					  	 enemigo.agresive =  Math.round(Math.random() * 30);  
						}
						
						
					  	
					  	
					  	estado.enemys += 1; 
					  	estado.next = true;
					  	
					  	flota.flota_enemiga.push(enemigo);
					  };
						
						
					  	motor.pos_x = posicion_x;
					  	
					  	return flota;
				}
			
			function draw(delta){
		
				cleanCtx();	
				ctx.fillStyle = "rgba(211, 211, 211, .7)";				
				ctx.fillText("Enemigos/Enemy: " + estado.enemys, 10, 105);			
				ctx.fillText("Puntuacion/Score: " + estado.score, 10,135);
				ctx.fillText("vidas: " + nave.lives, 10, 115);
				
				// nave
				if(nave.lives > 0){
										
					draw_ship(nave,delta); 
				}else{ 
					ctx.fillText("Fin del Juego / Game Over" , 10, 115);
					estado.gameOver = true;
				}
				
				// enemy 
				
				for (var z=0; z < flotaArray.length; z++)
				 {
					 var flota_tmp = flotaArray[z];					
					 flota_tmp.ejecutar(delta);
					 
					
				};
				
				//armas
				// draw_bullet(delta,  enemy_tmp);
				 draw_enemy_bullet(delta);
				 nave_draw_bullet(delta);	
				
				if(estado.colision)
				{
					explodeAnim(delta, ctx);
					
				}			
				
			}
			
			
			
			function draw_ship(nave,delta)
			{
				var posx = delta/1.5;
		
				
				// mover izquierda 			
				if(nave.move_min_x && nave.x > 10){
					nave.x = nave.x - posx;
				}
				// mover derecha 
				if(nave.move_max_x && nave.x < 850){
					nave.x = nave.x + posx;
				}
				
				if(nave.shoot){
					var weapon = new Bullet();
					motor.animationShoot = true;
				 	nave.shoot = false; 
					weapon.live = true;
				    weapon.x = nave.x;
				    weapon.how = "N"; 
				    nave_weapon_array.push(weapon);
				   
				}
				
				ctx.drawImage(nave.imagen,nave.x,nave.y);  
			}
			
			
			
			
			function nave_draw_bullet(delta){
				var speed = delta /30;	
				for (var i=0; i < nave_weapon_array.length; i++) {					
					var bullet = nave_weapon_array[i]; 
					bullet.draw(delta);
				}
				
			}
						
			function draw_enemy_bullet(delta){
				
				var speed = delta /290;				
							
				for (var i=0; i < special_weapon.length; i++) {
					var bullet = special_weapon[i]; 
					bullet.draw(delta);
										
					nave.collide(bullet);	
				};
			}
						
			function check_collision(objeto, enemy_tmp){	
				
				if(objeto.live){
						var enemy_x_area = enemy_tmp.x + enemy_tmp.imagen.width; 
						var enemy_y_area = enemy_tmp.y + enemy_tmp.imagen.height; 
						
						if(objeto.position != null){
							
							for (var i=0; i < objeto.position.length; i++) {
							  var loc = objeto.position[i];
							  var obj_x = loc.x;
							  var obj_y = loc.y;
							  
							  if((obj_x >= enemy_tmp.x && obj_x <= enemy_x_area)  
								&& (obj_y >= enemy_tmp.y && obj_y <= enemy_y_area))
							{														
								estado.colision = true; 
								objeto.live = false;		
								return true; 				
							}
							   
							};
							
							
						}  
						
						
						if((objeto.x >= enemy_tmp.x && objeto.x <= enemy_x_area)  
							&& (objeto.y >= enemy_tmp.y && objeto.y <= enemy_y_area))
							{														
								estado.colision = true; 
								objeto.live = false;		
								return true; 				
							}
				}
				return false;
			}
			
			
			function draw_enemy(enemy_tmp, delta){
				
				//drawing 
				enemy_tmp.get_shoot();
				enemy_tmp.shoot = intelE(nave, enemy_tmp);
				if(enemy_tmp.shoot == 3){ enemy_tmp.disparar(); }
				
				draw_object(enemy_tmp,delta, enemy_tmp.style);					
			}
			
			function manage_enemy(enemy_tmp, delta){
				
				if(enemy_tmp.style != "D" ||enemy_tmp.style != "Z"){
				if(estado.enemys < 12){
					enemy_tmp.style = "T";
				}
				if(estado.enemys < 5){
					enemy_tmp.style = "F";
				}
				
				}
				
				enemy_tmp.get_shoot();
				enemy_tmp.shoot = intelE(nave, enemy_tmp);		
				  
				
				if(enemy_tmp.shoot == 3){
					 enemy_tmp.disparar();
				 
					
				}
					enemy_tmp.paint()
					//draw_object(enemy_tmp,delta, enemy_tmp.style);	
				
					
			}
			
		
			function intelE(nave, enemy_tmp){
				
				
				if(enemy_tmp.shoot != 2) return enemy_tmp.shoot; 
					
				
				var enemy_x_area = enemy_tmp.x + enemy_tmp.imagen.width;  
			
				
				
				if((nave.x >= enemy_tmp.x && nave.x <= enemy_x_area)) {
					return 3; 
				}else return  enemy_tmp.shoot;
			}
		
			
			
			
			function draw_object(enemigo,delta, mover)
			{
				ctx.save(); 
			 	posy = delta / 80;
			 	
			 
			 	
			 	enemigo.y += posy; 				
				enemigo.x += enemigo.orientacion;
				
				ctx.drawImage(enemigo.imagen,enemigo.x,enemigo.y);  
				ctx.restore();
			}
			
			
			function cleanCtx() {
			
				// Clear display
				ctx.save();
				ctx.fillStyle = "rgba(0, 0, 0, .7)";
				ctx.fillRect(0, 0, canvas.width, canvas.height);
				ctx.restore();
			}
			
			
		
	</script>
	</head>

	<body onload="init()">
		<canvas id="canvas" width="900" height="600">
			Browser incompatible with canvas / incompatible con canvas.
		</canvas>
	</body>
</html>
